#include "sched.h"

static unsigned schedule_locked[CFG_CORE_NUM];
unsigned need_resched[CFG_CORE_NUM];
AstralTask locker[CFG_CORE_NUM];

void mark_need_resched(int core)
{
    need_resched[core]++;
}

void clean_need_resched(int core)
{
    need_resched[core] = 0;
}

int need_reschedule(int core)
{
    return need_resched[core];
}


boolean is_sched_disabled(int core)
{
    if(0 == schedule_locked[core])
    {
        return False;
    }
    return True;
}


int get_system_state(int core);

void disable_preempt(int core)
{
    FORBIT_LOCAL_INT(irqstatus);
    if(get_system_state(core) == 0)
    {
        if(schedule_locked[core] == 0)
        {
            locker[core] = get_curr_task();
        }
    }
    schedule_locked[core]++;
    RESUME_LOCAL_INT(irqstatus);
}

void restore_preempt(int core)
{
    FORBIT_LOCAL_INT(irqstatus);
    schedule_locked[core]--;
    if(schedule_locked[core] == 0)
    {
        locker[core] = NULL;
    }
    RESUME_LOCAL_INT(irqstatus);

    if (0 != schedule_locked[core])
    {
        return;   
    }
    if (need_resched[core])
    {
        // TODO: is in thread context ?
        AstralTask curr = get_curr_task();
        need_resched[core] = 0;
        if (curr)
        {
            state_change(curr, PREEMPTED, True);
        }
    }
}

